package com.platform.usercenter.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.platform.basicdata.api.remote.RemoteBasicdataService;
import com.platform.basicdata.api.remote.vo.DicAgent;
import com.platform.basicdata.api.remote.vo.DicCarrier;
import com.platform.common.core.constant.HttpStatus;
import com.platform.common.core.constant.SecurityConstants;
import com.platform.common.core.constant.UserConstants;
import com.platform.common.core.domain.R;
import com.platform.common.core.domain.entity.SysDept;
import com.platform.common.core.domain.entity.SysRole;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.domain.model.DataPermissionDTO;
import com.platform.common.core.domain.model.LoginUser;
import com.platform.common.core.domain.model.SysUserVo;
import com.platform.common.core.exception.ServiceException;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.utils.bean.BeanUtils;
import com.platform.common.core.utils.poi.ExcelUtil;
import com.platform.common.core.web.controller.BaseController;
import com.platform.common.core.web.domain.AjaxResult;
import com.platform.common.core.web.page.TableDataInfo;
import com.platform.common.log.annotation.Log;
import com.platform.common.log.enums.BusinessType;
import com.platform.common.security.annotation.InnerAuth;
import com.platform.common.security.annotation.RequiresPermissions;
import com.platform.common.security.service.TokenService;
import com.platform.common.security.utils.SecurityUtils;
import com.platform.constants.SysUserConstants;
import com.platform.system.api.remote.api.RemoteSystemService;
import com.platform.system.api.remote.vo.SysDictData;
import com.platform.usercenter.config.ConfigConstants;
import com.platform.usercenter.domain.*;
import com.platform.usercenter.domain.dto.SelectOptionDTO;
import com.platform.usercenter.domain.dto.SysOrganizationDeptDTO;
import com.platform.usercenter.domain.dto.SysUserDTO;
import com.platform.usercenter.domain.dto.SysUserInfoDTO;
import com.platform.usercenter.domain.query.SysRoleQuery;
import com.platform.usercenter.domain.query.SysUserDeptQuery;
import com.platform.usercenter.domain.vo.*;
import com.platform.usercenter.mapper.SysOrganizationDeptMapper;
import com.platform.usercenter.service.*;
import com.platform.usercenter.utils.TreeAdapterUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户管理
 *
 * @author: wcs
 * @date: 2025-04-10 10:37:00
 **/
@Slf4j
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysOrganizationDeptService sysOrganizationDeptService;

    @Resource
    private ISysPostService postService;

    @Resource
    private ISysPermissionService permissionService;

    @Resource
    private ISysUserAirportService sysUserAirportService;

    @Resource
    private ISysUserDeptService sysUserDeptService;

    @Resource
    private TokenService tokenService;

    @Resource
    private RemoteBasicdataService remoteBasicdataService;

    @Resource
    private RemoteSystemService remoteSystemService;

    @Resource
    ISysDeptTaxService iSysDeptTaxService;

    @Resource
    ImService imService;

    @Resource
    ConfigConstants configConstants;

    @Resource
    private ISysOrganizationService sysOrganizationService;

    @Resource
    private SysOrganizationDeptMapper sysOrganizationDeptMapper;


    @Resource
    private ISysOrganizationPermissionService organizationPermissionService;

    @Resource
    private ISysUserCommonService sysUserCommonService;

    @Resource
    private SysOrgDeptUserService sysOrgDeptUserService;

    /**
     * 解鎖用戶信息
     */
    @RequiresPermissions("system:user:unlock")
    @PostMapping("/unlockUser")
    public AjaxResult unlockUser(@RequestBody UnlockUserVO unlockUserVO) {
        userService.unLockUser(unlockUserVO);
        return AjaxResult.success();
    }

    /**
     * 免权限获取用户列表
     */
    @GetMapping("/noPermissionList")
    public TableDataInfo noPermissionList(SysUser user) {
        startPage();
        List<SysUser> list = userService.noPermissionList(user);
        return getDataTable(list);
    }


    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 菜单权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        // 功能权限集合--登录将全部组织下的功能权限都返回，后续切换部门会针对功能权限进行过滤
        List<DataPermissionDTO> dataPermissions = permissionService.getDataPermissions(sysUser);

        //获取用户组织集合
        List<SysOrganization> organizationList = permissionService.getOrgIdPermission(sysUser);
        Set<Long> orgIds = organizationList.stream().map(SysOrganization::getOrgId).collect(Collectors.toSet());

        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setOrgIds(orgIds);
        sysUserVo.setPermissions(permissions);
        sysUserVo.setModifyPwdTime(sysUser.getModifyPwdTime());
        if (ObjectUtils.isNotEmpty(sysUser.getOrgId())) {
            sysUserVo.setOrgId(sysUser.getOrgId());
            List<SysOrganization> collect = organizationList.stream().filter(item -> Objects.equals(sysUser.getOrgId(), item.getOrgId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(collect)) {
                sysUserVo.setOrgName(collect.get(0).getOrgName());
            }
        }
        //获取用户类型
        SysOrganization organization = sysOrganizationService.selectSysOrganizationByOrgId(sysUser.getOrgId());
        if (StringUtils.isNotNull(organization)) {
            if (StringUtils.isNotEmpty(organization.getLoginUserDeptType())) {
                sysUserVo.setLoginUserDeptType(organization.getLoginUserDeptType());
            }
            if (StringUtils.isNotEmpty(organization.getLoginUserTypeFefCode())) {
                sysUserVo.setLoginUserTypeFefCode(organization.getLoginUserTypeFefCode());
            }
        }
        List<SysOrganizationDeptDTO> sysOrganizationDeptList = sysOrganizationDeptMapper.selectSysOrganizationDeptListByUserId(sysUser.getUserId());
        Set<Long> deptIds = sysOrganizationDeptList.stream().map(SysOrganizationDeptDTO::getDeptId).collect(Collectors.toSet());
        sysUserVo.setLoginDeptIds(new ArrayList<>(deptIds));
        sysUserVo.setDataPermissions(dataPermissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取当前用户信息--旧版本
     */
    @InnerAuth
    @GetMapping("/infoOld/{username}")
    public R<LoginUser> infoOld(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        SysUserDeptQuery deptQuery = new SysUserDeptQuery();
        deptQuery.setUserId(sysUser.getUserId());
        deptQuery.setDeptId(sysUser.getDeptId());
        List<SysUserDept> sysUserDeptList = sysUserDeptService.selectSysUserDeptList(deptQuery);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        sysUserVo.setModifyPwdTime(sysUser.getModifyPwdTime());
        sysUserVo.setLoginDeptIds(sysUser.getDeptIds());
        if (sysUserDeptList != null && sysUserDeptList.size() > 0) {
            sysUserVo.setLoginUserDeptType(sysUserDeptList.get(0).getUserDeptType());
            sysUserVo.setLoginUserTypeFefCode(sysUserDeptList.get(0).getUserDeptTypeRefCode());
        }
        return R.ok(sysUserVo);
    }

    /**
     * 获取用户信息
     */
    @InnerAuth
    @GetMapping("/user/infoWithUserId")
    public R<LoginUser> getUserInfoByUserId(@RequestBody SysUser user) {
        if (user.getUserId() == null) {
            return R.fail("参数缺失");
        }
        SysUser sysUser = userService.selectUserById(user.getUserId());
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户不存在");
        }
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUserid(user.getUserId());
        sysUserVo.setUsername(user.getUserName());
        return R.ok(sysUserVo);
    }

    /**
     * 获取用户信息
     */
    @PostMapping("/user/getInfoByUserId")
    public R<LoginUser> getInfoBYUserId(@RequestBody SysUser user) {
        if (user.getUserId() == null) {
            return R.fail("参数缺失");
        }
        SysUser sysUser = userService.selectUserById(user.getUserId());
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户不存在");
        }
        List<SysOrganization> organizationList = permissionService.getOrgIdPermission(sysUser);
        Set<Long> orgIds = organizationList.stream().map(SysOrganization::getOrgId).collect(Collectors.toSet());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUserid(user.getUserId());
        sysUserVo.setUsername(sysUser.getUserName());
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setOrgId(sysUser.getOrgId());
        sysUserVo.setOrgIds(orgIds);
        return R.ok(sysUserVo);
    }


    /**
     * 获取当前用户信息_根据手机号获取
     */
    @InnerAuth
    @GetMapping("/infoByPhonenumber/{phonenumber}")
    public R<LoginUser> infoByPhonenumber(@PathVariable("phonenumber") String phonenumber) {
        SysUser sysUser = userService.selectByPhonenumber(phonenumber);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("手机号错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 菜单权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        // 功能权限集合--登录将全部组织下的功能权限都返回，后续切换部门会针对功能权限进行过滤
        List<DataPermissionDTO> dataPermissions = permissionService.getDataPermissions(sysUser);

        //获取用户组织集合
        List<SysOrganization> organizationList = permissionService.getOrgIdPermission(sysUser);
        Set<Long> orgIds = organizationList.stream().map(SysOrganization::getOrgId).collect(Collectors.toSet());

        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setOrgIds(orgIds);
        sysUserVo.setPermissions(permissions);
        sysUserVo.setModifyPwdTime(sysUser.getModifyPwdTime());
        if (ObjectUtils.isNotEmpty(sysUser.getOrgId())) {
            sysUserVo.setOrgId(sysUser.getOrgId());
            List<SysOrganization> collect = organizationList.stream().filter(item -> Objects.equals(sysUser.getOrgId(), item.getOrgId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(collect)) {
                sysUserVo.setOrgName(collect.get(0).getOrgName());
            }
        }
        //获取用户类型
        SysOrganization organization = sysOrganizationService.selectSysOrganizationByOrgId(sysUser.getOrgId());
        if (StringUtils.isNotNull(organization)) {
            if (StringUtils.isNotEmpty(organization.getLoginUserDeptType())) {
                sysUserVo.setLoginUserDeptType(organization.getLoginUserDeptType());
            }
            if (StringUtils.isNotEmpty(organization.getLoginUserTypeFefCode())) {
                sysUserVo.setLoginUserTypeFefCode(organization.getLoginUserTypeFefCode());
            }
        }
        List<SysOrganizationDeptDTO> sysOrganizationDeptList = sysOrganizationDeptMapper.selectSysOrganizationDeptListByUserId(sysUser.getUserId());
        Set<Long> deptIds = sysOrganizationDeptList.stream().map(SysOrganizationDeptDTO::getDeptId).collect(Collectors.toSet());
        sysUserVo.setLoginDeptIds(new ArrayList<>(deptIds));
        sysUserVo.setDataPermissions(dataPermissions);
        return R.ok(sysUserVo);
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!userService.checkUserNameUnique(sysUser)) {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     * 用户绑定openid
     *
     * @param phonenumber
     * @param openid
     * @return
     */
    @PostMapping("/bindOpenid")
    public R<LoginUser> bindOpenid(@RequestParam("phonenumber") String phonenumber, @RequestParam("openid") String openid) {
        if (StringUtils.isAnyBlank(phonenumber, openid)) {
            return R.fail("手机号和openid不能为空！");
        }
        SysUser sysUser = userService.selectByPhonenumber(phonenumber);
        if (ObjectUtils.isEmpty(sysUser)) {
            //用户为空 无法绑定 需要添加手机号或者联系负责人添加用户信息
            return R.fail("请联系管理员");
        }
        // 不为空 绑定到现有账号
        userService.userBindOpenId(openid, sysUser.getUserId());
        return R.ok(userService.selectByOpenId(openid));
    }

    /**
     * 微信小程序-用户解绑
     *
     * @param phonenumber
     * @return
     */
    @InnerAuth
    @PostMapping("/unbindOpenid")
    public R<Boolean> unbindOpenid(@RequestParam("phonenumber") String phonenumber, @RequestParam("openid") String openid) {
        if (StringUtils.isAnyBlank(phonenumber)) {
            return R.fail("手机号不能为空！");
        }
        SysUser sysUser = userService.selectByPhonenumber(phonenumber);
        if (sysUser == null) {
            return R.fail("该用户不存在！");
        }

        if (StringUtils.isNotEmpty(openid) && openid.equals(sysUser.getOpenId())) {
            userService.userUnBindOpenId(sysUser.getUserId());
            return R.ok(true, "解绑成功！");
        }
        return R.ok(true, "解绑成功！");
    }


    /**
     * 获取当前用户信息_根据openId获取
     */
    //@InnerAuth
    @GetMapping("/selectByOpenId/{openId}")
    public R<LoginUser> selectByOpenId(@PathVariable("openId") String openId) {
        return R.ok(userService.selectByOpenId(openId));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = userService.selectUserById(loginUser.getSysUser().getUserId());
        List<SysOrganizationDeptDTO> sysOrganizationDeptList = sysOrganizationDeptMapper.selectSysOrganizationDeptListByUserId(loginUser.getUserid());
        Set<Long> deptIds = sysOrganizationDeptList.stream().map(SysOrganizationDeptDTO::getDeptId).collect(Collectors.toSet());
        Long deptId = deptIds.stream().findFirst().orElse(null);
        if (Objects.isNull(user.getDeptId())) {
            user.setDeptId(deptId);
        }
        // 角色集合
        Set<String> roles = permissionService.getRoleDeptPermission(user, loginUser.getOrgId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        // 获取当前登入用户部门信息
        SysUserDeptQuery deptQuery = new SysUserDeptQuery();
        deptQuery.setUserId(loginUser.getUserid());
        deptQuery.setOrgId(loginUser.getOrgId());//当前用户登入部门
        List<SysUserDept> sysUserDeptList = sysUserDeptService.selectSysUserDeptList(deptQuery);
        //当前登入用户所属组织
        List<SysOrganization> organizationList = permissionService.getOrgIdPermission(user);
        AjaxResult ajax = AjaxResult.success();
        // 获取组织税号
        try {
            List<SysDeptTax> ListTax = iSysDeptTaxService.selectUserDeptTax(user.getDeptId());
            if (ListTax != null && ListTax.size() > 0) {
                List<String> taxs = new ArrayList<>();
                for (SysDeptTax vo : ListTax) {
                    taxs.add(vo.getTaxId());
                }
                ajax.put("taxId", taxs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Object deptObject;
        if (CollectionUtils.isNotEmpty(sysUserDeptList)) {
            SysUserDept sysUserDept = sysUserDeptList.get(0);
            if (StringUtils.isBlank(sysUserDept.getUserDeptTypeRefCode())
                    && StringUtils.isNotBlank(loginUser.getLoginUserTypeFefCode())) {
                sysUserDept.setUserDeptTypeRefCode(loginUser.getLoginUserTypeFefCode());
            }
            deptObject = sysUserDept;
        } else {
            deptObject = new ArrayList<>();
        }
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("userDept", deptObject);
        ajax.put("organizationList", organizationList);
        ajax.put("loginOrgId", loginUser.getOrgId());
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfoByOrgId/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("orgId") Long orgId) {
        if (ObjectUtils.isEmpty(orgId)) {
            return AjaxResult.error("组织信息缺失！");
        }
        SysUser user = userService.selectUserById(SecurityUtils.getLoginUser().getSysUser().getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRoleDeptPermission(user, orgId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        // 功能权限集合--组织下的功能权限都返回
        List<DataPermissionDTO> dataPermissions = permissionService.getDataPermissions(user);
        /**
         * 获取当前登入用户部门信息
         */
        SysUserDeptQuery deptQuery = new SysUserDeptQuery();
        deptQuery.setUserId(user.getUserId());
        deptQuery.setDeptId(user.getDeptId());//当前用户登入部门
        List<SysUserDept> sysUserDeptList = sysUserDeptService.selectSysUserDeptList(deptQuery);


        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("userDept", CollectionUtils.isNotEmpty(sysUserDeptList) ? sysUserDeptList.get(0) : new ArrayList<>());
        return ajax;
    }

    /**
     * 获取登录用户信息
     *
     * @return
     */
    @GetMapping("getLoginInfo")
    public AjaxResult getLoginInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        AjaxResult ajax = AjaxResult.success();

        List<SysOrganizationDeptDTO> sysOrganizationDeptList = sysOrganizationDeptMapper.selectSysOrganizationDeptListByUserId(loginUser.getUserid());
        Set<Long> deptIds = sysOrganizationDeptList.stream().map(SysOrganizationDeptDTO::getDeptId).collect(Collectors.toSet());
        ajax.put("userId", loginUser.getUserid());
        ajax.put("userName", loginUser.getUsername());
        ajax.put("loginDeptId", deptIds);
        ajax.put("orgId", loginUser.getOrgId());
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
//    @RequiresPermissions("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {

        Long optUserId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();

        List<SysPost> posts = postService.selectPostAll();//全部岗位
        List<SysRole> roles = null;

        if (SysUser.isAdmin(optUserId) || isAdminRole(optUserId)) {
            roles = roleService.selectRoleAll();
        } else {
            //操作人拥有的角色 或者 创建的角色
            roles = roleService.selectRolesByUserIdOrCreated(new SysRoleQuery());
        }
        List<SysRole> ownRoles = SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList());
        ajax.put("roles", ownRoles);
        ajax.put("posts", posts);
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            // 查询多组织情况
//            List<UserDeptVo> userDepts = userDeptService.selectUserDeptVoList(userId,optUserId,SecurityUtils.getLoginUser().getLoginDeptId());
            UserVo userVo = new UserVo();
            BeanUtils.copyBeanProp(userVo, sysUser);
//            userVo.setUserDepts(userDepts);
            ajax.put(AjaxResult.DATA_TAG, userVo);
//            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            List<Long> roleIds = sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
            ajax.put("roleIds", roleIds);
            // 判断不拥有的角色 列表 start
            if (roleIds != null && roleIds.size() > 0) {
                List<SysRole> exceptRoles = new ArrayList<>();
                for (Long roleId : roleIds) {
                    Boolean exceptFlag = true;
                    if (ownRoles != null && ownRoles.size() > 0) {
                        for (SysRole ownRole : ownRoles) {
                            Long ownRoleId = ownRole.getRoleId();
                            if (roleId.longValue() == ownRoleId.longValue()) {
                                exceptFlag = false;
                            }
                        }
                    }
                    if (exceptFlag) {
                        SysRole exceptRole = roleService.selectRoleById(roleId);
                        exceptRole.setStatus("1");
                        exceptRoles.add(exceptRole);
                    }
                }
                if (exceptRoles != null && exceptRoles.size() > 0) {
                    ajax.put("exceptRoles", exceptRoles);
                }
            }
            // 判断不拥有的角色 列表 end
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:user:add")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody UserVo userVo) {
//        logger.info("新增用户开始！！！！>>>>>"+ userVo.toString());
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        Long orgId = SecurityUtils.getLoginUser().getOrgId();
        if (!sysUserCommonService.isAdmin(userId)) {
            userVo.setOrgId(orgId);
        }
        SysUser user = new SysUser();
        BeanUtils.copyBeanProp(user, userVo);
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
//        logger.info("开始校验强密码>>>>>"+DateUtil.getNow());
        boolean matches = user.getPassword().matches(SysUserConstants.PW_PATTERN);
//        logger.info("结束校验强密码>>>>>"+DateUtil.getNow());
        if (!matches) {
            return error("密码必须是8-20位且包含大小写字母、数字、特殊字符！");
        }
        userVo.setCreateBy(SecurityUtils.getUsername());
        userVo.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userVo.setModifyPwdTime(new Date());
        int res = userService.insertUserVo(userVo);
        if (res > 0 && ObjectUtil.isNotEmpty(userVo.getOrgId())) {
            SysOrgDeptUser orgDeptUser = new SysOrgDeptUser();
            orgDeptUser.setUserId(userVo.getUserId());
            orgDeptUser.setOrgId(userVo.getOrgId());
            orgDeptUser.setIsDelete(SysUserConstants.N);
            orgDeptUser.setCreateBy(SecurityUtils.getUsername());
            orgDeptUser.setCreateTime(new Date());
            sysOrgDeptUserService.insertSysOrgDeptUser(orgDeptUser);
        }
        if (configConstants.isImSwitch()) {
            try {
                Long[] userids = new Long[]{userVo.getUserId()};
                imService.registerBatchUsers(userids);
            } catch (Exception e) {
                logger.error("****更新IM用户密码异常：{}", e.getMessage());
                e.printStackTrace();
            }
        }
        return toAjax(res);
    }

    /**
     * 修改用户
     */
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody UserVo userVo) {
        SysUser user = new SysUser();
        BeanUtils.copyBeanProp(user, userVo);
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        userVo.setUpdateBy(SecurityUtils.getUsername());
        int res = userService.updateUserVo(userVo);
        try {
            if (!StringUtils.isEmpty(userVo.getUserName())) {
                imService.updateImUserInfo(userVo.getUserName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(res);
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system:user:remove")
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return error("当前用户不能删除");
        }
        int res = userService.deleteUserByIds(userIds);
        try {
            imService.deleteBatchImUser(userIds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(res);
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setModifyPwdTime(new Date());
        int res = userService.resetPwd(user);
        try {
            imService.updateImUserPwd(user.getUserId(), user.getPassword());
        } catch (Exception e) {
            logger.error("****更新IM用户{}密码异常：{}", user.getUserId(), e.getMessage());
            e.printStackTrace();
        }
        return toAjax(res);
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:query")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysOrganizationDept dept) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (SysUser.isAdmin(loginUser.getUserid()) || isAdminRole(loginUser.getUserid())) {
            return success(sysOrganizationDeptService.selectDeptTreeList4Admin(dept));
        } else {
            return success(sysOrganizationDeptService.selectDeptTreeList(dept));
        }
    }

    /**
     * 免权限获取部门树列表
     */
    @GetMapping("/noPermissionsDeptTree")
    public AjaxResult noPermissionsDeptTree(SysOrganizationDept dept) {
        return success(sysOrganizationDeptService.noPermissionsDeptTree(dept));
    }

    /**
     * 获取部门树列表-准备废弃
     */
    @GetMapping("/userAllDeptTree")
    public AjaxResult userAllDeptTree() {
        return success(sysOrganizationDeptService.selectUserAllDeptTree());
    }

    /**
     * 获取可切换用户组织列表
     */
    @GetMapping("/userAllOrgTree")
    public AjaxResult userAllOrgTree() {
        return success(sysOrganizationService.userAllOrgTree());
    }


    /**
     * 获取用户的组织机构-平铺
     *
     * @return 组织信息
     */
    @GetMapping("/userAllOrg")
    public AjaxResult userAllOrg() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        return success(permissionService.getOrgIdPermission(sysUser));
    }


    /**
     * 获取部门树列表 (小程序)
     */
    @GetMapping("/userAllDept")
    public AjaxResult userAllDept() {
        return success(sysOrganizationDeptService.selectUserAllDept());
    }

    /**
     * 变更登录组织
     *
     * @param dept
     * @return
     */
    @PostMapping("/changeLoginDept")
    public AjaxResult changeLoginDept(@RequestBody SysDept dept) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        loginUser.setLoginDeptIds(getDeptIdsByUserId(loginUser.getUserid()));
        loginUser.getSysUser().setDeptId(dept.getDeptId());

        SysUserDeptQuery deptQuery = new SysUserDeptQuery();
        deptQuery.setDeptId(dept.getDeptId());
        deptQuery.setUserId(loginUser.getUserid());
        List<SysUserDept> sysUserDeptList = sysUserDeptService.selectSysUserDeptList(deptQuery);
        if (sysUserDeptList != null && sysUserDeptList.size() > 0) {
            loginUser.setLoginUserDeptType(sysUserDeptList.get(0).getUserDeptType());
            loginUser.setLoginUserTypeFefCode(sysUserDeptList.get(0).getUserDeptTypeRefCode());
        }
        tokenService.refreshToken(loginUser);

        return success();
    }

    /**
     * 切换组织
     *
     * @param organization 组织
     * @return
     */
    @PostMapping("/changeLoginOrg")
    public AjaxResult changeLoginOrg(@RequestBody SysOrganization organization) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        loginUser.setOrgId(organization.getOrgId());
        // 重新获取数据角色权限
        SysUser sysUser = new SysUser();
        sysUser.setUserId(loginUser.getSysUser().getUserId());
        sysUser.setOrgId(organization.getOrgId());
        List<DataPermissionDTO> dataPermissions = permissionService.getDataPermissions(sysUser);
        loginUser.setDataPermissions(dataPermissions);
        // 更新角色数据
        List<SysRole> currentOrgUserRoles = userService.getCurrentOrgUserRoles(sysUser);
        if (Objects.nonNull(loginUser.getSysUser())) {
            loginUser.getSysUser().setRoles(currentOrgUserRoles);
        }
        //获取用户类型
        SysOrganization organizationInfo = sysOrganizationService.selectSysOrganizationByOrgId(sysUser.getOrgId());
        if (StringUtils.isNotNull(organizationInfo)) {
            loginUser.setOrgName(organizationInfo.getOrgName());
            if (StringUtils.isNotEmpty(organizationInfo.getLoginUserDeptType())) {
                loginUser.setLoginUserDeptType(organizationInfo.getLoginUserDeptType());
            }
            if (StringUtils.isNotEmpty(organizationInfo.getLoginUserTypeFefCode())) {
                loginUser.setLoginUserTypeFefCode(organizationInfo.getLoginUserTypeFefCode());
            }
        }
        tokenService.refreshToken(loginUser);
        return success();
    }

    /**
     * 设备信息ip
     */
    @InnerAuth
    @PostMapping("/addIp")
    public R<Boolean> addIp(@RequestBody SysUser user) {
        return R.ok(userService.addIp(user.getUserId(), user.getLoginIp()));
    }

    /**
     * 通过User查询 用户归属机构
     */
//    @InnerAuth
    @PostMapping("/getUserDept")
    public R<List<SysOrganizationDeptDTO>> getUserDept(@RequestBody SysUserDeptQuery query) {
        List<SysOrganizationDeptDTO> sysUserDeptList = sysOrganizationDeptMapper.selectSysOrganizationDeptListByUserId(query.getUserId());
        return R.ok(sysUserDeptList);
    }

    @PostMapping("/userDeptTypeRefInfo")
    public AjaxResult userDeptTypeRefInfo(@RequestBody JSONObject jsonObject) {
        String userDeptType = (String) jsonObject.get("userDeptType");
        List<Map<String, Object>> retList = new ArrayList<>();
        if (userDeptType != null) {
            LoginUser loginUser = SecurityUtils.getLoginUser();

            SysUserDeptQuery deptQuery = new SysUserDeptQuery();
            List<SysUserDept> sysUserDeptList = null;
            if (!SysUser.isAdmin(loginUser.getUserid()) && !isAdminRole(loginUser.getUserid())) {
                deptQuery.setDeptIds(loginUser.getLoginDeptIds());
                deptQuery.setUserId(loginUser.getUserid());
                deptQuery.setUserDeptType(userDeptType);
                sysUserDeptList = sysUserDeptService.selectSysUserDeptList(deptQuery);
            }

            if (UserConstants.USER_DEPT_TYPE_AIR_AGENCY.equals(userDeptType)) {
                R<List<DicAgent>> resultAgentList = remoteBasicdataService.getAgentList(new DicAgent(), SecurityConstants.INNER);
                if (HttpStatus.SUCCESS != resultAgentList.getCode()) {
                    throw new ServiceException(resultAgentList.getCode() + resultAgentList.getMsg());
                }
                List<DicAgent> agentList = resultAgentList.getData();
                if (agentList != null && agentList.size() > 0) {
                    for (DicAgent agent : agentList) {
                        getCodeMapList(retList, agent, sysUserDeptList);
                    }
                }
            } else if (UserConstants.USER_DEPT_TYPE_AIR_AIRLINE.equals(userDeptType)) {
                R<List<DicCarrier>> resultCarrierList = remoteBasicdataService.getCarrierList(new DicCarrier(), SecurityConstants.INNER);
                if (HttpStatus.SUCCESS != resultCarrierList.getCode()) {
                    throw new ServiceException(resultCarrierList.getCode() + resultCarrierList.getMsg());
                }
                List<DicCarrier> carrierList = resultCarrierList.getData();
                if (carrierList != null && carrierList.size() > 0) {
                    for (DicCarrier carrier : carrierList) {
                        getCodeMapList(retList, carrier, sysUserDeptList);
                    }
                }
            }
        }


        return success(retList);
    }


    private boolean isAdminRole(Long userId) {
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        if (CollectionUtil.isEmpty(roles)) {
            return false;
        }
        return roles.stream().filter(SysRole::isFlag).anyMatch(r -> "GLY".equals(r.getRoleKey()) || "GLYALL".equals(r.getRoleKey()));
    }

    private List<Map<String, Object>> getCodeMapList(List<Map<String, Object>> retList, Object obj, List<SysUserDept> sysUserDeptList) {


        Map<String, Object> codeMap = new HashMap<>();
        String code = null;
        String name = null;

        if (obj instanceof DicAgent) {
            code = ((DicAgent) obj).getAgentCode();
            name = ((DicAgent) obj).getNameFull();
        }
        if (obj instanceof DicCarrier) {
            code = ((DicCarrier) obj).getCarrier();
            name = ((DicCarrier) obj).getNameFull();
        }
        if (sysUserDeptList != null) {
            for (SysUserDept dept : sysUserDeptList) {
                if (dept.getUserDeptTypeRefCode().equals(code)) {
                    codeMap.put("code", code);
                    codeMap.put("name", name);
                    retList.add(codeMap);
                }
            }
        } else {
            codeMap.put("code", code);
            codeMap.put("name", name);
            retList.add(codeMap);
        }

        return retList;

    }


    @PostMapping("/userAirportCodes")
    public AjaxResult userAirportCodes() {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        //登录用户的机场数据
        List<SysUserAirport> sysUserAirports = null;
        SysUserAirport queryVo = new SysUserAirport();

        if (!SysUser.isAdmin(loginUser.getUserid()) && !isAdminRole(loginUser.getUserid())) {

            queryVo.setUserId(loginUser.getUserid());
            queryVo.setDeptIds(loginUser.getLoginDeptIds());
            sysUserAirports = sysUserAirportService.selectSysUserAirportList(queryVo);
        }

        List<Map<String, Object>> retList = new ArrayList<>();
        R<List<SysDictData>> airportList = remoteSystemService.getDictInfo("sys_base_airportcode", SecurityConstants.INNER);
        if (HttpStatus.SUCCESS != airportList.getCode()) {
            throw new ServiceException(airportList.getCode() + airportList.getMsg());
        }
        if (airportList.getData() != null && airportList.getData().size() > 0) {
            List<SysDictData> list = airportList.getData();
            for (SysDictData airportVo : list) {
                Map<String, Object> airportCodeMap = new HashMap<>();

                String code = airportVo.getDictValue();
                String name = airportVo.getDictLabel();

                if (sysUserAirports != null) {
                    for (SysUserAirport userAirport : sysUserAirports) {
                        if (userAirport.getAirportCode().equals(code)) {
                            airportCodeMap.put("code", code);
                            airportCodeMap.put("name", name);
                            retList.add(airportCodeMap);
                        }
                    }
                } else {
                    airportCodeMap.put("code", code);
                    airportCodeMap.put("name", name);
                    retList.add(airportCodeMap);
                }
            }
        } else {

            if (sysUserAirports != null) {
                for (SysUserAirport userAirport : sysUserAirports) {
                    Map<String, Object> airportCodeMap = new HashMap<>();
                    airportCodeMap.put("code", userAirport.getAirportCode());
                    airportCodeMap.put("name", "");
                    retList.add(airportCodeMap);
                }
            }
        }
        return success(retList);
    }

    @PostMapping("/getUserDeptByIdCard")
    public R<List<SysOrganizationDeptDTO>> getUserDeptByIdCard(@RequestParam("idCard") String idCard) {
        List<SysOrganizationDeptDTO> sysUserDeptList = sysOrganizationDeptMapper.selectSysUserDeptListByIdCard(idCard);
        return R.ok(sysUserDeptList);
    }

    @RequestMapping("/selectUserInfoByUserNames")
    public AjaxResult selectUserInfoByUserNames(String[] usernames) {
        if (usernames == null || usernames.length == 0) {
            return AjaxResult.success();
        }
        List<SysUser> list = userService.selectUserInfoByUserNames(usernames);
        for (SysUser u : list) {
            u.setUserName(u.getUserName().toLowerCase());
        }
        Map<String, SysUser> map = list.stream().collect(Collectors.toMap(SysUser::getUserName, Function.identity(), (key1, key2) -> key2));
        return AjaxResult.success(map);
    }

    /**
     * IM获取用户列表
     */
    @GetMapping("/listIm")
    public TableDataInfo listIm(UserVo user) {
        startPage();
        List<UserVo> list = userService.selectAllUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取全部部门树列表
     */
    @GetMapping("/selectAllDeptList")
    public AjaxResult selectAllDeptList(SysOrganizationDept dept) {
        return success(sysOrganizationDeptService.selectAllDeptList(dept));
    }

    /**
     * 获取当前组织部门树列表
     */
    @GetMapping("/selectCurrentOrgDeptList")
    public AjaxResult selectCurrentOrgDeptList(SysOrganizationDept dept) {
        return success(sysOrganizationDeptService.selectCurrentOrgDeptList(dept));
    }


    @RequestMapping("/selectUserInfoByUserIds")
    public AjaxResult selectUserInfoByUserIds(Long[] userIds) {
        if (userIds == null || userIds.length == 0) {
            return AjaxResult.success();
        }
        List<SysUser> list = userService.selectUserInfoByUserIds(userIds);
        Map<Long, SysUser> map = list.stream().collect(Collectors.toMap(SysUser::getUserId, Function.identity(), (key1, key2) -> key2));
        return AjaxResult.success(map);
    }

    /***
     *  用户 id 获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/getUserById/{userId}")
    public AjaxResult getUserById(@PathVariable Long userId) {
        return AjaxResult.success(userService.selectUserById(userId));
    }

    /***
     *  用户 id 获取用户信息 远程调用
     * @param userId
     * @return
     */
    @GetMapping("remote/getUserById/{userId}")
    public R<SysUserVo> getUserInfo(@PathVariable Long userId) {
        return R.ok(userService.getUserInfo(userId));
    }


    //---------------------------------------------------用户体系改造----------------------------------------------//


    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysUserVO user) {
        startPage();
        List<SysUserVO> list = userService.selectUserVOList(user);
        return getDataTable(list);
    }

    /**
     * 用户管理-获取组织/部门/岗位树
     */
    @GetMapping("/getOrgTree")
    public AjaxResult getOrgTree() {
        List<SysUserOrgTreeVO> list = userService.getOrgTree();
        return AjaxResult.success(list);
    }


    /**
     * 获取组织部门树列表
     */
    @GetMapping("orgDeptTree")
    public AjaxResult orgDeptTree() {
        List<SysOrgDeptTreeVO> list = userService.orgDeptTree();
        return AjaxResult.success(list);
    }


    /**
     * 获取组织树部门树列表
     */
    @GetMapping("orgTreeDeptTree")
    public AjaxResult orgTreeDeptTree() {
        List<SysOrgDeptTreeVO> list = userService.orgTreeDeptTree();
        return AjaxResult.success(list);
    }

    /**
     * 审批中台获取组织部门树列表
     */
    @GetMapping("/approval/getApprovalOrgDeptTree")
    public AjaxResult getApprovalOrgDeptTree() {
        List<SysOrgDeptTreeVO> list = userService.approvalOrgDeptTree();
        return AjaxResult.success(list);
    }

    /**
     * 审批中台获取组织部门树列表-不包含
     */
    @GetMapping("/approval/getApprovalOrgNonDeptTree")
    public AjaxResult getApprovalOrgNonDeptTree() {
        List<SysOrgDeptTreeVO> list = userService.approvalOrgNonDeptTree();
        return AjaxResult.success(list);
    }

    /**
     * 用户管理-根据组织/部门/岗位ID获取用户列表
     * 包含下级部门岗位
     * 结果去重用户
     */
    @PostMapping("/getUserInfoById")
    public TableDataInfo getUserInfoById(SysUserVO user) {
        return userService.getUserInfoById(user);
    }

    /**
     * 获取用户列表--通过组织/部门/岗位
     */
    @GetMapping("/listByOrg")
    public TableDataInfo listByOrg(SysUserVO user) {
        startPage();
        List<SysUserVO> list = userService.selectUserVOList(user);
        return getDataTable(list);
    }


    /**
     * 用户管理-修改用户组织详情
     */
    @GetMapping("/getUserOrgInfo/{userId}")
    public AjaxResult getUserOrgInfo(@PathVariable(value = "userId") Long userId) {
        // 获取用户组织，部门，角色，岗位信息
        return AjaxResult.success(userService.getUserOrgInfo(userId));
    }

    /**
     * 用户管理-加入组织
     */
    @PostMapping("/joinOrg")
    public AjaxResult joinOrg(@RequestBody SysUserDTO userDTO) {
        return AjaxResult.success(userService.joinOrg(userDTO));
    }

    /**
     * 用户管理-修改组织
     */
    @PostMapping("/editOrg")
    public AjaxResult editOrg(@RequestBody SysUserDTO userDTO) {
        return AjaxResult.success(userService.editOrg(userDTO));
    }

    /**
     * 用户管理-设为分级管理员
     */
    @PostMapping("setGraded")
    public AjaxResult setGraded(@RequestBody SysUserDTO userDTO) {
        return AjaxResult.success(userService.setGraded(userDTO));
    }

    /**
     * 获取当前用户组织下拉框选择--暂定
     */
    @GetMapping("/getUserOrgList")
    public AjaxResult getUserOrgList() {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        if (sysUserCommonService.isAdmin(userId)) {

        }
        return AjaxResult.success();
    }

    /**
     * 用户管理-设置分级管理员列表
     */
    @PostMapping("/getGradedList")
    public AjaxResult getGradedList(@RequestParam(value = "orgIds") Long[] orgIds) {
        if (StringUtils.isEmpty(orgIds)) {
            return AjaxResult.error("参数缺失!");
        }
        List<SysUserInfoDTO> userInfoDTOS = new ArrayList<>();
        SysRoleQuery query = new SysRoleQuery();
        query.setRoleFlag(SysUserConstants.ROLE_FLAG_2);
        query.setOrgIds(orgIds);
        List<SysRole> sysRoles = roleService.selectRoleList(query);
        if (CollectionUtil.isNotEmpty(sysRoles)) {
            for (SysRole role : sysRoles) {
                SysUserInfoDTO infoDTO = new SysUserInfoDTO();
                infoDTO.setOrgId(role.getOrgId());
                infoDTO.setGradedRoleId(role.getRoleId());
                infoDTO.setGradedRoleName(role.getRoleName());
                userInfoDTOS.add(infoDTO);
            }
        }
        return AjaxResult.success(userInfoDTOS);
    }


    /**
     * 用户管理-权限预览
     */
    @PostMapping("/previewPerm")
    public AjaxResult previewPerm(@RequestParam(value = "userId") Long userId, @RequestParam(value = "orgId") Long orgId) {
        return AjaxResult.success(userService.previewPerm(userId, orgId));
    }


    /**
     * 获取组织下拉列表
     */
    @GetMapping("/getOrgList")
    public AjaxResult getOrgList() {
        return AjaxResult.success(sysOrganizationService.selectSysOrganizationTree());

    }

    /**
     * 获取组织下的部门列表
     */
    @GetMapping("/getOrgDeptTree/{orgId}")
    public AjaxResult getOrgDeptTree(@PathVariable(value = "orgId") Long orgId) {
        SysOrganizationDept deptQuery = new SysOrganizationDept();
        deptQuery.setOrgId(orgId);
        deptQuery.setIsDelete(SysUserConstants.N);
        List<SysOrganizationDept> depts = sysOrganizationDeptMapper.selectSysOrganizationDeptList(deptQuery);
        if (CollectionUtil.isNotEmpty(depts)) {
            depts = TreeAdapterUtil.buildTree(depts, SysOrganizationDept.class, null);
        }
        return AjaxResult.success(depts);
    }


    /**
     * 根据用户id获取组织下拉列表
     */
    @GetMapping("/getOrgListByUserId")
    public AjaxResult getOrgListByUserId() {


        return AjaxResult.success();
    }

    /**
     * 用户管理-组织页签新增用户
     */
    @GetMapping("/getOrgUser/{userId}")
    public AjaxResult getOrgUser(@PathVariable(value = "userId") Long userId) {
        Map<String, Object> userMap = new HashMap<>();
        SysUser sysUser = userService.selectUserById(userId);
        if (ObjectUtils.isNotEmpty(sysUser)) {
            userMap.put("user", sysUser);
        }
        // 封装组织信息
        List<SysUserOrgInfoVO> userOrgInfoVOS = userService.getUserOrgInfo(userId);
        if (CollectionUtil.isNotEmpty(userOrgInfoVOS)) {
            userMap.put("orgInfo", userOrgInfoVOS);
        }
        return AjaxResult.success(userMap);
    }


    /**
     * 获取用户角色信息
     *
     * @param orgId
     * @return
     */
    @GetMapping("/getRoleByUserByOrg/{orgId}")
    public AjaxResult getRoleByUserByOrg(@PathVariable(value = "orgId") Long orgId) {
        Map<String, Object> userMap = new HashMap<>();
        List<SysRole> sysRoles = userService.getRoleByOrg(orgId);
        userMap.put("roles", sysRoles);
        return AjaxResult.success(userMap);
    }


    /**
     * 获取用户组织角色-层级
     *
     * @param orgId
     * @return
     */
    @GetMapping("/getOrgRoleByUserUser/{orgId}")
    public AjaxResult getOrgRoleByUserUser(@PathVariable(value = "orgId") Long orgId) {
        return AjaxResult.success(userService.getOrgRoleByUserUser(orgId));
    }

    /**
     * 用户管理-组织页签新增用户
     */
    @PostMapping("/addOrgUser")
    public AjaxResult addOrgUser(@RequestBody SysUserDTO userDTO) {


        SysUser user = new SysUser();
        BeanUtils.copyBeanProp(user, userDTO);
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
//        logger.info("开始校验强密码>>>>>"+DateUtil.getNow());
        boolean matches = user.getPassword().matches(SysUserConstants.PW_PATTERN);
//        logger.info("结束校验强密码>>>>>"+DateUtil.getNow());
        if (matches == false) {
            return error("密码必须是8-20位且包含大小写字母、数字、特殊字符！");
        }
        userDTO.setCreateBy(SecurityUtils.getUsername());
        userDTO.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userDTO.setModifyPwdTime(new Date());
        int res = userService.addOrgUser(userDTO);
        if (configConstants.isImSwitch()) {
            try {
                Long[] userids = new Long[]{userDTO.getUserId()};
                imService.registerBatchUsers(userids);
            } catch (Exception e) {
                logger.error("****更新IM用户密码异常：{}", e.getMessage());
                e.printStackTrace();
            }
        }
        return toAjax(res);
    }

    /**
     * 用户管理-组织页签新增用户
     */
    @PostMapping("/editOrgUser")
    public AjaxResult editOrgUser(@RequestBody SysUserDTO userVo) {
        SysUser user = new SysUser();
        BeanUtils.copyBeanProp(user, userVo);
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        userVo.setUpdateBy(SecurityUtils.getUsername());
        int res = userService.editOrgUser(userVo);
        try {
            if (!StringUtils.isEmpty(userVo.getUserName())) {
                imService.updateImUserInfo(userVo.getUserName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(res);
    }


    /**
     * 用户管理-修改用户（用户页签用）
     */
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PutMapping("/editUser")
    public AjaxResult editUser(@Validated @RequestBody UserVo userVo) {
        SysUser user = new SysUser();
        BeanUtils.copyBeanProp(user, userVo);
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        userVo.setUpdateBy(SecurityUtils.getUsername());
        int res = userService.updateUserInfo(userVo);
        try {
            if (!StringUtils.isEmpty(userVo.getUserName())) {
                imService.updateImUserInfo(userVo.getUserName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(res);
    }


    /**
     * 用户管理-修改用户组织详情（用户页签用）
     */
    public AjaxResult editUserOrgInfo() {


        return AjaxResult.success();
    }


    /**
     * 用户管理-修改用户（组织页签用）
     */
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PutMapping("/editOrgUser")
    public AjaxResult editOrgUser(@Validated @RequestBody UserVo userVo) {
        SysUser user = new SysUser();
        BeanUtils.copyBeanProp(user, userVo);
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        userVo.setUpdateBy(SecurityUtils.getUsername());
        int res = userService.updateUserVo(userVo);
        try {
            if (!StringUtils.isEmpty(userVo.getUserName())) {
                imService.updateImUserInfo(userVo.getUserName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(res);
    }


    /**
     * 角色管理-数据权限分配下拉值
     */
    @PostMapping("/getOrgValueByKey")
    public AjaxResult getOrgValueByKey(@RequestParam(value = "orgId") Long orgId, @RequestParam(value = "key") String key) {

        if (ObjectUtil.isEmpty(orgId)) {
            return AjaxResult.error("组织id缺失！");
        }
        if (StringUtils.isEmpty(key)) {
            return AjaxResult.error("编码key缺失！");
        }

        Set<String> setValue = new HashSet<>();

        List<SelectOptionDTO> selectOptionDTOS = new ArrayList<>();

        SysOrganizationPermission permission = new SysOrganizationPermission();
        permission.setOrgId(orgId);
        permission.setCode(key);
        permission.setIsDelete(SysUserConstants.N);
        List<SysOrganizationPermission> organizationPermissions = organizationPermissionService.selectSysOrganizationPermissionList(permission);
        if (CollectionUtil.isNotEmpty(organizationPermissions)) {
            for (SysOrganizationPermission value : organizationPermissions) {
                if (StringUtils.isNotEmpty(value.getValue())) {
                    try {
                        JSONArray jsonArray = com.alibaba.fastjson.JSONObject.parseArray(value.getValue());
                        if (ObjectUtil.isNotEmpty(jsonArray)) {
                            List<SelectOptionDTO> optionDTOS = jsonArray.toJavaList(SelectOptionDTO.class);
                            if (CollectionUtil.isNotEmpty(optionDTOS)) {
                                selectOptionDTOS.addAll(optionDTOS);
                            }
                        }
                    } catch (Exception e) {
                        log.error("解析JSON数据异常{}", e.getMessage());

                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(selectOptionDTOS)) {
            selectOptionDTOS = selectOptionDTOS.stream()
                    .collect(Collectors.toMap(
                            p -> new AbstractMap.SimpleEntry<>(p.getLabel(), p.getValue()),
                            p -> p,
                            (p1, p2) -> p1
                    )).values().stream().collect(Collectors.toList());

        }
        return AjaxResult.success(selectOptionDTOS);
    }


    private List<Long> getDeptIdsByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            throw new ServiceException("用户id为空,请先登录");
        }
        List<SysOrganizationDeptDTO> sysOrganizationDeptList = sysOrganizationDeptMapper.selectSysOrganizationDeptListByUserId(userId);
        return sysOrganizationDeptList.stream().map(SysOrganizationDeptDTO::getDeptId).distinct().collect(Collectors.toList());
    }


    /**
     * 通过User查询 用户归属机构
     */
    @PostMapping("/getUserAirport")
    public R<List<SysUserAirport>> getUserAirport(@RequestBody SysUserAirport sysUserAirport) {
        List<SysUserAirport> sysUserAirportList = new ArrayList<>();
        try {
            Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
            Long orgId = SecurityUtils.getLoginUser().getOrgId();
            if (ObjectUtil.isNotEmpty(userId) && ObjectUtil.isNotEmpty(orgId)) {
                SysUserAirport query = new SysUserAirport();
                query.setUserId(userId);
                query.setOrgId(orgId);
                sysUserAirportList = sysUserAirportService.selectSysUserAirportListByRole(query);
            }
        } catch (Exception e) {
            log.error("获取用户角色权限机场异常{}", e.getMessage());
        }
        return R.ok(sysUserAirportList);
    }


}
